import axios from 'axios';
import {
    notification
} from 'ant-design-vue'
import Cookies from 'js-cookie'; // yarn add js-cookie
// 请求baseUrl
const BASE_URL = process.env.VUE_APP_REQUEST_BASE_URL

const initInstance = function (contentType) {
    let instance = axios.create({
        headers: {
            'content-type': contentType || 'application/json'
        },
        baseURL: BASE_URL,
        timeout: 30000,
        withCredentials: true //  每次请求携带用户凭证(cookie、HTTP身份验证和TLS客户端证书)
    })

    // 添加请求拦截器
    instance.interceptors.request.use(function (config) {
        // 请求头中添加 "X-Access-Token"，服务器从中获取token
        config.headers["X-Access-Token"] = Cookies.get('token')
        return config
    }, function (error) {
        // 对请求错误做些什么
        return Promise.reject(error)
    })

    // 添加响应拦截器
    instance.interceptors.response.use(function (response) {
        if (+response.data.code !== 200) {
            notification.error({
                message: '系统提示',
                description: response.data.message,
                duration: 4
            })
        }
        return response.data
    }, err => {
        let code = err.response.status;
        let msg = "系统出现错误,请刷新页面重试！"
        switch (+code) {
            case 401:
                msg = "token已失效，请重新登录"
                setTimeout(() => {
                    window.location.href = "/login";
                }, 300);
                break;
        }
        notification.error({
            message: '系统提示',
            description: msg,
            duration: 4
        })
    })
    return instance;
}



export default function (url, params, methods = "post") {
    const instance = initInstance();
    return new Promise((resolve, reject) => {
        let req = null
        if (methods === 'post') {
            req = instance.post(url, params)
        } else {
            req = instance.get(url, {
                params: params
            })
        }
        req.then(res => resolve(res)).catch(err => reject(err))
    })
}
// 用于上传文件 用form表单提交
export const formSubmit = function (url, form) {
    const instance = initInstance("multipart/form-data");
    return new Promise((resolve, reject) => {
        let req = null
        req = instance.post(url, form)
        req.then(res => resolve(res)).catch(err => reject(err))
    })
}
